package com.test02;

import com.test01.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

public class TestTransaction {
    public static void main(String[] args) {
        Connection cn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;

        try {
            cn = JdbcUtils.getConnection();

            cn.setAutoCommit(false); //开启事务，关闭自动提交

            String sql1 = "update users set name='zshh',email='24736743@qq.com' where id=1";
            pstm = cn.prepareStatement(sql1);
            pstm.executeUpdate();

//            int x = 1/0;  测试失败
            String sql2 = "update users set name='zshh',email='24736743@qq.com' where id=2";
            pstm = cn.prepareStatement(sql2);
            pstm.executeUpdate();

            cn.commit(); //提交事务
            System.out.println("提交成功");
        } catch (SQLException e) {
            try {
                cn.rollback(); //默认失败会回滚
                System.out.println("失败，回滚");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JdbcUtils.releaseConnection(cn,pstm,rs);
        }
    }
}
